package r25.room;

import org.slf4j.Logger;

import r25.character.ICharacter;
import r25.engine.Event;
import r25.engine.IEvent;
import r25.engine.IEvent.EVENT;
import r25.engine.IGameInstance;
import r25.engine.IGameInstance.CHARACTER_ACTION;
import r25.tools.LoggerHelper;

/**
 * As soon as you enter, this room locks itself from the inside and becomes
 * inaccessible (no one can enter for the rest of the game). After your second
 * action of the next turn, if your character is still there, you drown.
 * 
 * @author u211354
 * 
 */
public class FloodedChamber extends AbstractRoom {
	private static final Logger logger = LoggerHelper.getLogger();

	@Override
	public boolean isAccessible() {
		return !isVisible();
	}

	@Override
	public CHARACTER_ACTION onEnter(IGameInstance gi, ICharacter character)
			throws Exception {
		CHARACTER_ACTION rc = super.onEnter(gi, character);
		gi.pushEvent(new Event(EVENT.DIE_IN_FLOODED_ROOM, this, character));
		return rc;
	}

	@Override
	public void check(IGameInstance gi, boolean endOfTurn, IEvent s) {
		// may invalidate the event
		super.check(gi, endOfTurn, s);

		// process only own event DIE_IN_FLOODED_ROOM
		if (!EVENT.DIE_IN_FLOODED_ROOM.equals(s.getType()) || !s.isValid()) {
			return;
		}

		ICharacter character = s.getCharacter();
		if (!character.equals(gi.getCurrentCharacter())) {
			return;
		}

		logger.debug("Evaluating event {} for {}", s, character);
		logger.debug("  Event {} vs GTS {}", gi.getTurnIndex(),
				s.getTimeStamp());
		if (this.equals(character.getRoomIn())) {
			boolean isNextAction = endOfTurn
					&& ((gi.getTurnIndex() - s.getTimeStamp().getTurn()) == 1);
			if (isNextAction && character.isAlive()) {
				logger.debug("Triggered @{} event {}",
						gi.getCurrentStateTimeStamp(), s);
				// the character dies
				character.setAlive(false);
				gi.pushEvent(new Event(EVENT.DEATH, this, character));

				s.setValid(false);
			}

			// if "next turn" relative to the event is in the past, remove event
			if ((gi.getTurnIndex() - s.getTimeStamp().getTurn()) > 1) {
				s.setValid(false);
			}
		}
	}
}
